#!/usr/bin/python
#-*-encoding:utf-8-*-
import json
from test import Mongo
from mongoengine import *
from os import remove
from random import randint
import argparse

dbname="English"
collection="word"

word_file="eng.txt"
json_file="result.json"
word_document = {
                "word":StringField(unique=True),
                "meaning":StringField(),
                "learned":BooleanField(default=False)
                }
def randlist(*alist):
    index=randint(0,len(alist)-1)
    return alist[index]
def show(mode=""):
    words = Mongo(dbname,collection,**word_document)
    if mode=="masked":query={"learned":True}
    elif mode=="unmasked":query={"learned":False}
    else:query={}
    for i in words.find(**query):
        print "*"*25
        print i.word
        print i.meaning
        print "已记忆" if i.learned else "未记忆"
def txt_to_json(sr,dt):
    with open(sr,'r') as f:
            with open(dt,'w+') as j:
				j.write("[\n")
				for i in f:
					if i and i!="\n":
						j.write('{\n')
						#print i.split("\t\t")
						j.write('"word":'+'"%s",\n'%i.strip('\n').split("\t\t")[0])
						j.write('"meaning":'+'"%s"\n'%i.strip('\n').split("\t\t")[1])
						j.write("},\n")
				j.write('{}\n')
				j.write("]\n")
def json_to_db(sr,cover=True):   
    a=Mongo("English","word",**word_document)
    with open(sr,'r') as f:
        text = ''.join(f.readlines())
        js = json.loads(text)
        #print js
        for i in js:
            if not i:continue
            if cover:
                if a.findall(word=i["word"]):
                    a.update(i,word=i["word"])
                else:
                    a.insert(**i)
            else:
                if a.find(word=i["word"]):
                    continue
                else:
                    a.insert(**i) 
def study(count=1):
    db=Mongo("English","word",**word_document)
    words=db.find(learned=False)
    for i in range(count):
        word=randlist(*words)
        print "*"*25
        print word.word
        print word.meaning
def mark_learned(words):
    db = Mongo("English","word",**word_document)
    
    if isinstance(words,list):
        for word in words:  
            a = db.find(word=word)
            if not a:
                print "该单词不存在"
                return
            db.update({"learned":True},word=word)
    else:
        word=words
        a = db.find(word=word)
        if not a:
            print "该单词不存在"
            return
        db.update({"learned":True},word=word)
def unmark_learned(words):
    if isinstance(words,list):
        for word in words:
            db = Mongo("English","word",**word_document)
            a = db.find(word=word)
            db.update({"learned":False},word=word)
    else:
        word=words
        db = Mongo("English","word",**word_document)
        a = db.find(word=word)
        db.update({"learned":False},word=word)
def add(txt="",js=""):
    if txt:
        txt_to_json(txt,"tmp.json")
        json_to_db("tmp.json")
        remove("tmp.json")
        return True
    elif js:
        json_to_db(tmp.json)
        remove("tmp.json")
        return True
    else:
        raise Exception("需要指定txt或json文件")
        return False

parser = argparse.ArgumentParser()
parser.add_argument("-f",type=str,default="eng.txt")
parser.add_argument("-s",type=str,default="eng.txt")

word_file=parser.parse_args().f
#show()
#word_file="new_words.txt"
#txt_to_json(word_file,json_file)
if word_file!="eng.txt":
    add(word_file)
else:
    pass
#    print "study:"
#   study(5)
mark_learned("two")
mark_learned("China")
show("masked")
